﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using SIA.Allarms;
using System.Data;
using SIA.Configurators;

namespace SIA.DataBase.MySQL
{
    public class MySqlArchive : DBArchive
    {
        public MySqlArchive(IDictionaryProperty DBProperty)
            :base(DBProperty)
        {
        }

        public override void savePastAllarm(IAllarm allarme)
        {
            try
            {
                using (MySqlConnection  sqlConnection = new MySqlConnection( this.SqlConString ))
                {
                    sqlConnection.Open();
                    MySqlCommand sqlCommand = new MySqlCommand(
                        "INSERT INTO " + this.StoricAllarmsTable + "(NomeAllarme, Gruppo, DataOraON, DataOraOFF, DataOraACK, Comment) " +
                              "VALUES(?nomeAllarme, ?gruppo, ?dataOraON, ?dataOraOFF, ?dataOraACK, ?comment)", sqlConnection);

                    sqlCommand.Prepare();
                    sqlCommand.Parameters.AddWithValue("?nomeAllarme", allarme.Nome);
                    sqlCommand.Parameters.AddWithValue("?gruppo", allarme.Gruppo);
                    sqlCommand.Parameters.AddWithValue("?dataOraON", allarme.DataOraON);
                    sqlCommand.Parameters.AddWithValue("?dataOraOFF", allarme.DataOraOFF);
                    sqlCommand.Parameters.AddWithValue("?dataOraACK", allarme.DataOraACK);
                    sqlCommand.Parameters.AddWithValue("?comment", allarme.Commento);
                    sqlCommand.ExecuteNonQuery();
                    sqlConnection.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Errore su salvaAllarmeToDB: Salvataggio di " + allarme.ToString() + " in " + this.StoricAllarmsTable + ". " + ex.Message, ex);
            }
        }

        public override DataTable Select(string selectQuery)
        {
            using (MySqlConnection cn = new MySqlConnection(this._sqlConString))
            {
                //codice per l'apertura della connessione
                MySqlDataAdapter mda = new MySqlDataAdapter(selectQuery, cn);

                DataTable dt = new DataTable();
                mda.Fill(dt);                

                if (cn != null)
                {
                    cn.Close();
                    cn.Dispose();
                }

                return dt;
            }    
        }
    }
}
